import router from "@/router"

export const format = (shijianchuo: string | number | Date, type = 'yyyy-MM-dd hh:mm:ss') => {
    if (!shijianchuo) return '/'
    //shijianchuo是整数，否则要parseInt转换
    const time = new Date(shijianchuo)
    const y = time.getFullYear()
    const m = time.getMonth() + 1
    const d = time.getDate()
    const h = time.getHours()
    const mm = time.getMinutes()
    const s = time.getSeconds()
    const add0 = (m: number): string => {
        return m < 10 ? '0' + m : m + ''
    }
    switch (type) {
        case 'minDay':
            return y + '/' + add0(m) + '/' + '01'
        default:
            return type
                .replace('yyyy', y + '')
                .replace('MM', add0(m))
                .replace('dd', add0(d))
                .replace('hh', add0(h))
                .replace('mm', add0(mm))
                .replace('ss', add0(s))
    }
}

export const utilCheckPermission = (value: string[]): boolean => {
    const userInfo = getStorageUserInfo()
    if (value && value.length > 0) {
        const permissions = userInfo.permissions || []
        const hasPermission = permissions.some((permission: string) => {
            return value.includes(permission)
        })

        return hasPermission
    } else {
        return false
    }
}
export const utilLogout = () => {
    localStorage.setItem("siteUserInfo", JSON.stringify({}));
    router.push({ name: 'login' })
}
export const getStorageUserInfo = () => {
    const userInfo = JSON.parse(localStorage.getItem('siteUserInfo') || "{}")
    return userInfo
}
export const downLoadFile = (blob: Blob, name: string) => {
    const url = URL.createObjectURL(blob);
    // 创建一个a标签用于触发下载
    const downloadLink = document.createElement('a');
    downloadLink.href = url;
    downloadLink.download = name; // 指定下载文件的名称

    // 添加链接到文档并模拟点击
    document.body.appendChild(downloadLink);
    downloadLink.click();

    // 清理并移除元素和URL引用
    document.body.removeChild(downloadLink);
    URL.revokeObjectURL(url);
}
/**
 * 外部资源引入 js
 * @author duan 2017-01-19
 * @param  {[type]}   url      [description]
 * @param  {Function} callback [description]
 * @return {[type]}            [description]
 */
export const loadJS = (url: string, id: string, callback: () => void) => {
    const heads = document.getElementsByTagName('head')
    let head
    if (heads && heads.length) {
        head = heads[0]
    } else {
        head = document.body
    }
    const script: any = document.createElement('script')

    script.type = 'text/javascript'
    script.id = id
    head.appendChild(script)
    script.onload = script.onreadystatechange = function () {
        if (!this.readyState || this.readyState === 'complete' || this.readyState === 'loaded') {
            if (callback) callback()
        }
    }
    script.src = url
}
export const echartLoad = (callback?: () => void) => {
    if ((window as any).echarts) {
        callback && callback()
    } else {
        loadJS('./js/echarts.min.js', 'echart', () => {
            callback && callback()
        })
    }
}
export const highchartLoad = (callback?: () => void) => {
    if ((window as any).Highcharts) {
        callback && callback()
    } else {
        loadJS('./js/highcharts.min.js', 'echart', () => {
            loadJS('./js/highcharts-3d.min.js', 'echart', () => {
                callback && callback()
            })
        })

        
    }
}
// num：要转换的数字，x: 保留x 为小数，x 需大于0
export const toDecimalNoZero = (num: number, x: number = 2) => {
    const b = Math.pow(10, x)
    var f = Math.round(num * b) / b
    var s = f.toString()
    return s
}
/**
 * 截取字符串前N位
 * @param text 
 * @param maxLength 
 * @returns 
 */
export const truncateText = (text, maxLength = 20) => {
    if (text.length > maxLength) {
        return text.substring(0, maxLength) + '...';
    }
    return text;
}
/**
 * 加载地图
 * @param callback 
 */
export const mapLoad = (callback?: () => void) => {
    const mapV1 = document.getElementById('mapV1')
    if (mapV1) {
        mapV1.parentNode?.removeChild(mapV1)
        const plus = document.getElementById('amap_plus_js')
        plus && plus.parentNode?.removeChild(plus)
            ; (window as any).AMap = null
    }
    if ((window as any).AMap) {
        callback && callback()
    } else {
        ; (window as any)._AMapSecurityConfig = {
            securityJsCode: '35b150be528be81218bf90a644b96cac'
        }
        loadJS('https://webapi.amap.com/maps?v=2.0&key=64b0df2fba0d46a311dd6ddba2bf0255&plugin=AMap.Geocoder', 'mapV2', () => {
            callback && callback()
        })
    }
}
export const toYuan = (num) => {
    return Number(toDecimalNoZero(num / 100))
}
export const toFen = (num) => {
    return Number(toDecimalNoZero(num * 100))
}

